<?php
namespace app\home\controller;

use think\Controller;

class Captcha extends Controller
{
    private $result = [
        'msg'  => '验证码发送成功',
        'code' => 1,
        'data' => [],
    ];

    private $captchaAction = 'register';

    //图形验证码
    public function index()
    {
        $captcha = new \think\captcha\Captcha([
            'length'   => 4, 
            'fontSize' => 64,    
            'useNoise' => true, 
            'useCurve' => false,
            'codeSet'  => 'abcdefghijkmnopkrstuvwxyz',
        ]);
        $captcha->fontttf = '4.ttf';
        return $captcha->entry();
    }

    //注册帐号发送动态码（短信/邮箱）
    public function register()
    {
        $this->captchaAction = 'register';

        return $this->send();
    }

    //重设密码发送动态码
    public function reset()
    {
        $this->captchaAction = 'reset';

        return $this->send();
    }

    //发送注册验证码（短信/邮箱）
    private function send()
    {
        $captcha = input('post.captcha/s');
        if(!captcha_check($captcha)){
            $this->result['msg']  = '验证码错误';
            $this->result['code'] = -1;
            return json($this->result);
        };
        //手机短信
        if(config('user.type') == 'mobile'){
            return $this->sendMobile(input('post.mobile/s'));
        }
        //邮箱验证
        return $this->sendEmail(input('post.email/s'));
    }

    //短信验证码
    private function sendMobile($mobile='')
    {
        if(!\think\facade\Validate::isMobile($mobile)){
            $this->result['msg']  = '请输入正确的手机号';
            $this->result['code'] = -1;
            return json($this->result);
        }
        //发送验证码
        $model = model('common/Captcha','loglic');
        if(!$model->mobile($mobile, $this->captchaAction)){
             $this->result['msg']  = $model->getError();
             $this->result['code'] = -2;
             return json($this->result);
        }
        //返回发送结果
        return json($this->result);
    }

    //邮箱验证码
    private function sendEmail($email='')
    {
        if(!\think\facade\Validate::isEmail($email)){
            $this->result['msg']  = '请输入正确的邮箱地址';
            $this->result['code'] = -1;
            return json($this->result);
        }
        //发送验证码
        $model = model('common/Captcha','loglic');
        if(!$model->email($email, $this->captchaAction)){
             $this->result['msg']  = $model->getError();
             $this->result['code'] = -2;
             return json($this->result);
        }
        //返回发送结果
        return json($this->result);
    }
}